package com.wxl.common.http

import android.app.Dialog
import android.content.Context
import android.text.TextUtils
import androidx.annotation.CallSuper
import com.alibaba.fastjson.JSONObject
import com.lzy.okgo.callback.Callback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.wxl.common.AppContext
import com.wxl.common.base.DataBean
import com.wxl.common.util.Toll
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.net.UnknownServiceException


/**
 * create file time : 2021/3/9
 * create user : wxl
 * subscribe :
 */
abstract class AbsHttpCallback : Callback<Any> {

    protected open var loadDialog: Dialog? = null
    private var tag:Any? = null


    override fun onSuccess(response: Response<Any>?) {
        try {
            response?.body()?.let { success(it as DataBean) }
        } catch (e : Exception){
            error(e)
        }
    }

    override fun onFinish() {
        if (loadDialog != null) {
            if (loadDialog?.isShowing!!) {
                loadDialog?.dismiss()
            }
        }
        tag?.let {
            OkGoApi.api.cancelTag(tag.toString())
        }
    }

    override fun downloadProgress(progress: Progress?) {

    }

    override fun uploadProgress(progress: Progress?) {

    }

    override fun convertResponse(response: okhttp3.Response?): Any? {

        try {

            response ?: return null

            val data: String = response.body()?.string().toString()

            response.takeIf { it.isSuccessful }?.takeIf { !TextUtils.isEmpty(data) }?.let {
                return JSONObject.parseObject(data, DataBean::class.java)
            }

        } catch (e: Exception) {
            Toll.toll("服务器返回数据错误")
            error(e)
        }

        return null
    }

    override fun onError(response: Response<Any>?) {
        response?.exception?.let { error(it) }
    }

    override fun onCacheSuccess(response: Response<Any>?) {

    }

    override fun onStart(request: Request<Any, out Request<Any, Request<*, *>>>?) {
        this.tag = request?.tag
        loadDialog = showLoadDialog(AppContext.appContext.getCurrentActivity())
        loadDialog ?: return
        loadDialog.takeIf { !it?.isShowing!! }?.show()
    }


    abstract fun success(data: DataBean)

    @CallSuper
    open fun error(e: Throwable) {
        if (e is SocketTimeoutException || e is UnknownHostException || e is UnknownServiceException || e is SocketException) {
            Toll.toll("网络连接失败,请检查网络")
        }
    }


    protected open fun showLoadDialog(context: Context?): Dialog? {
        return null
    }



}
